package org.qs.webservice.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.qs.webservice.content.IReadContent;
import org.qs.webservice.dao.user.UsBalanceMapper;
import org.qs.webservice.dao.user.UsMemberVotesMapper;
import org.qs.webservice.dao.user.UsRechargeMapper;
import org.qs.webservice.dao.user.UsUserMapper;
import org.qs.webservice.dao.user.UserGradeMapper;
import org.qs.webservice.domain.UsAccountRecharge;
import org.qs.webservice.domain.UsBalance;
import org.qs.webservice.domain.UsMemberVotes;
import org.qs.webservice.domain.UsUser;
import org.qs.webservice.exception.QSReadException;
import org.qs.webservice.service.IreadMemcacheService;
import org.qs.webservice.service.UserService;
import org.qs.webservice.sign.DESCoder;
import org.qs.webservice.sign.MD5;
import org.qs.webservice.util.DateUtil;
import org.qs.webservice.util.IReadUtils;
import org.qs.webservice.util.IdWorker;
import org.qs.webservice.util.SendmailUtil;
import org.qs.webservice.util.StringUtils;
import org.qs.webservice.vo.AccountRecharge;
import org.qs.webservice.vo.PageData;
import org.qs.webservice.vo.UserInfo;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {
	@Resource
	private UsUserMapper usUserMapper;
	@Resource
	private UsBalanceMapper usBalanceMapper;
	@Resource
	private UsMemberVotesMapper usMemberVotesMapper;
	@Resource
	private UsRechargeMapper usRechargeMapper;
	@Resource
	private IreadMemcacheService ireadMemcacheService;
	@Resource
	private UserGradeMapper userGradeMapper;
	//private static final Logger logger = Logger.getLogger(UserService.class.getName());
	public String registerUser(String user_name, String mobile_num,
			String password, String device_identifier, String promot,String email,String regist_ip,String sign) {
		Map<String,Object> ret = new HashMap<String,Object>();
		UserInfo userInfo = new UserInfo();
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		try{
			
			if(StringUtils.isNullOrEmpty(user_name)||StringUtils.isNullOrEmpty(password)||StringUtils.isNullOrEmpty(device_identifier)||StringUtils.isNullOrEmpty(promot)||StringUtils.isNullOrEmpty(email)){
				ret.put("code", 403);
				ret.put("reason","参数错误");
				return IReadUtils.beanToJson(ret);
			}else{
				UsUser user = usUserMapper.getCustomUserByUsername(user_name);
				
				if(user==null){
					UsUser user_email = usUserMapper.getCustomUserByEmail(email);
					if(user_email!=null){
						ret.put("reason", "邮箱已注册");
						ret.put("code", 403);
						return IReadUtils.beanToJson(ret);
					}
					user = new UsUser();
					IdWorker worker2 = new IdWorker(1);
					user.setUser_id(worker2.nextId());
					user.setMobile_num(mobile_num);
					user.setUser_name(user_name);
					user.setEmail(email);
					user.setRegist_ip(regist_ip);
					user.setUser_password(MD5.getMD5(MD5.getMD5(password)));
					user.setDevice_identifier(device_identifier);
					user.setPromot_channel(promot);
					user.setRegist_source(5);
					user.setCreate_time(new Date());
					usUserMapper.addUser(user);
					UsBalance balance = new UsBalance();
					balance.setUser_id(user.getUser_id());
					balance.setBalance(IReadContent.register_balance);
					balance.setVersion(1);
					balance.setModify_time(new Date());
					user.setIs_author(0);
					usBalanceMapper.addBalance(balance);
					String str = user.getUser_id()+":"+device_identifier;
					//rsa加密
				    String signStr = IReadUtils.getSign(str);
		            tokenMap.put("token",signStr);
		            tokenMap.put("code",200);
		            userInfo = setUser(user);
					tokenMap.put("content", userInfo);
					
					ireadMemcacheService.setUserSignIn(user.getUser_id().toString()+device_identifier, signStr);
					
					
					if(!StringUtils.isNullOrEmpty(sign)){
		    			String uuid=IReadUtils.getUserIdByToken(sign, ireadMemcacheService, device_identifier);
		    			String key =uuid+":"+device_identifier;
		    			String source_id = (String) ireadMemcacheService.get(key);
		    			if(!StringUtils.isNullOrEmpty(source_id)){
		    				UsUser usBand = usUserMapper.getSsoUserByUserId(user.getUser_id(),Integer.valueOf(source_id));
		    				if(usBand!=null){
		    					usBand = new UsUser();
		    					usBand.setOpen_uid(uuid);
		    					usBand.setCreate_time(new Date());
		    					usBand.setModify_time(new Date());
		    					usBand.setBand_status(1);
		    					usBand.setOpen_id(Integer.valueOf(source_id));
		    					usBand.setUser_id(user.getUser_id());
		    					usUserMapper.updateUserBand(usBand);
		    				}else{
		    					usBand.setUser_id(user.getUser_id());
		    					usUserMapper.updateUserBand(usBand);
		    				}
		    			}
		    			 ireadMemcacheService.delete(key);
		    		}
					
					
					
					return  IReadUtils.beanToJson(tokenMap);
					
				}else{
					ret.put("reason", "用户已注册");
					ret.put("code", 403);
					return IReadUtils.beanToJson(ret);
				}
				
			}
		}catch(Exception e){
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("mobile", mobile_num);
			errorJson.put("user_name", user_name);
			errorJson.put("password", password);
			errorJson.put("device_identifier", device_identifier);
			errorJson.put("promot", promot);
			QSReadException.printf(e, "获取验证码异常！",errorJson);
			ret.put("reason", "服务器错误");
            ret.put("code", 403);
			return IReadUtils.beanToJson(ret);
		}
	}
	@Override
	public String customLogin(String user_name, String password,
			String device_identifier,String sign) {
		UserInfo userInfo = new UserInfo();
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(StringUtils.isNullOrEmpty(user_name)||StringUtils.isNullOrEmpty(password)){
				map.put("code", "403");
				map.put("reason", "参数错误");
				return IReadUtils.beanToJson(map);
			}
			
			UsUser usUser = usUserMapper.getCustomUserByUsername(user_name);
			if (usUser == null) {
				map.put("code", "403");
				map.put("reason", "用户不存在");
				return IReadUtils.beanToJson(map);
			} else {// 登录成功，返回token值
				/*if(StringUtils.isNullOrEmpty(usUser.getUser_password())){
					//密码错误
					map.put("code", "403");
					map.put("password", "请初始化密码");
					return IReadUtils.beanToJson(map);
				}*/
				if(usUser.getUser_password().equals(MD5.getMD5(MD5.getMD5(password)))){
					//rsa加密
					String userStr = usUser.getUser_id()+":"+device_identifier;
					//rsa加密
					String signStr = IReadUtils.getSign(userStr);
				    
				    
		            
		            userInfo = setUser(usUser);
			//		System.out.println("login token:"+signStr);
			//		System.out.println("lusUser.getUser_id().toString()+device_identifier:"+usUser.getUser_id().toString()+device_identifier);
		            ireadMemcacheService.setUserSignIn(usUser.getUser_id().toString()+device_identifier, signStr);
		            
		            
		        	if(!StringUtils.isNullOrEmpty(sign)){
		    			String uuid=IReadUtils.getUserIdByToken(sign, ireadMemcacheService, device_identifier);
		    			String key =uuid+":"+device_identifier;
		    			String source_id = (String) ireadMemcacheService.get(key);
		    			if(!StringUtils.isNullOrEmpty(source_id)){
		    				UsUser usBand = usUserMapper.getSsoUserByUserId(usUser.getUser_id(),Integer.valueOf(source_id));
		    				if(usBand!=null){
		    					usBand = new UsUser();
		    					usBand.setOpen_uid(uuid);
		    					usBand.setCreate_time(new Date());
		    					usBand.setModify_time(new Date());
		    					usBand.setBand_status(1);
		    					usBand.setOpen_id(Integer.valueOf(source_id));
		    					usBand.setUser_id(usUser.getUser_id());
		    					usUserMapper.updateUserBand(usBand);
		    				}else{
		    					usBand.setUser_id(usUser.getUser_id());
		    					usUserMapper.updateUserBand(usBand);
		    				}
		    			}
		    			 ireadMemcacheService.delete(key);
		    		}
		            
		            
		            tokenMap.put("code",200);
		            tokenMap.put("content", userInfo);
		            tokenMap.put("token", signStr);
		            return IReadUtils.beanToJson(tokenMap);
				}else{
					//密码错误
					map.put("code", "403");
					map.put("reason", "密码错误");
					return IReadUtils.beanToJson(map);
				}

			}
			
		} catch (Exception e) {
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("user_name", user_name);
			errorJson.put("password", password);
			errorJson.put("device_identifier", device_identifier);
			QSReadException.printf(e, "普通登录异常！",errorJson);
			map.put("code", "403");
			map.put("reason", "参数错误");

			return IReadUtils.beanToJson(map);
		}
		
	}
	@Override
	public String getMe(String token, String device_identifier) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		UserInfo userInfo = new UserInfo();
		String userId=IReadUtils.getUserIdByTokenWithoutEffective(token);
		String memkey = (String) ireadMemcacheService.getUserSignIn(userId+device_identifier);
		if(memkey!=null&&token.equals(memkey)){
			//ireadMemcacheService.setUserSignIn(userId+device_identifier, token);
			UsUser user = usUserMapper.getCustomUserByUserid(Long.valueOf(userId));	
			if(user!=null){
				userInfo = setUser(user);
				tokenMap.put("code", 200);
				tokenMap.put("content", userInfo);
				return IReadUtils.beanToJson(tokenMap); 
			}else{
				tokenMap.put("code", 403);
				tokenMap.put("reason", "用户不存在");
				return IReadUtils.beanToJson(tokenMap); 
			}
		   
		}else{
			tokenMap.put("code", 403);
			tokenMap.put("reason", "token失效");
			return IReadUtils.beanToJson(tokenMap); 
		}
		
	}
	@Override
	public String ssoLogin(String user_identifier, String device_identifier,
			String nick_name, String source, String promot, String tokenStr,
			String image_url,String regist_ip) {
		UserInfo userInfo = new UserInfo();
		
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int temp=0;
		UsUser usUser = null;
		try {
			//获取相对应的绑定信息
			UsUser usBand = usUserMapper.getSsoUserByUserIdentifier(user_identifier,Integer.valueOf(source));
			if (usBand == null) {
				usBand = new UsUser();
				usBand.setOpen_uid(user_identifier);
				usBand.setCreate_time(new Date());
				usBand.setModify_time(new Date());
				usBand.setBand_status(1);
				usBand.setOpen_id(Integer.valueOf(source));
				usBand.setUser_id(0L);
				temp=1;
			}else if(usBand.getBand_status()!=1){
				tokenMap.put("code", 403);
				tokenMap.put("reason", "账号被禁用");
			}
			//咪咕用户已存在数据表
			if(temp!=1){
				UsUser bandUser = usUserMapper.getCustomUserByUserid(usBand.getUser_id());
				if(bandUser!=null){
					usUser=bandUser;
				}
			}
			
			
			if(usUser==null){
				usUser = new UsUser();
				
				usUser.setCreate_time(new Date());
				usUser.setDevice_identifier(device_identifier);
				usUser.setImage_url(image_url);
				usUser.setIs_author(0);
				IdWorker worker2 = new IdWorker(7);
				usUser.setUser_id(worker2.nextId());
				usUser.setUser_name(usUser.getUser_id().toString());
				nick_name="书友_"+usUser.getUser_id();
				usUser.setUser_name(nick_name);
				usUser.setPromot_channel(promot);
				usUser.setRegist_ip(regist_ip);
				usUser.setRegist_source(Integer.valueOf(source));
				usUserMapper.addUser(usUser);
				usBand.setUser_id(usUser.getUser_id());
				usUserMapper.updateUserBand(usBand);
				UsBalance balance = new UsBalance();
				balance.setUser_id(usUser.getUser_id());
				balance.setBalance(IReadContent.register_balance);
				usBalanceMapper.addBalance(balance);
			}
			
			//转换成json

			//rsa加密
			String userStr = usUser.getUser_id()+":"+device_identifier;
			//rsa加密
			String signStr = IReadUtils.getSign(userStr);
            
            
			userInfo = setUser(usUser);
			
            
         //   System.out.println("sso:"+device_identifier+":"+signStr);
            ireadMemcacheService.setUserSignIn(usUser.getUser_id().toString()+device_identifier, signStr);
            tokenMap.put("code", 200);
            tokenMap.put("content", userInfo);
            tokenMap.put("token", signStr);
			return IReadUtils.beanToJson(tokenMap);
		} catch (Exception e) {
			//String user_identifier, String device_identifier,
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("user_identifier", user_identifier);
			errorJson.put("device_identifier", device_identifier);
			errorJson.put("nick_name", nick_name);
			errorJson.put("source", source);
			errorJson.put("promot", promot);
			errorJson.put("promot", promot);
			errorJson.put("tokenStr", tokenStr);
			QSReadException.printf(e, "第三方登录异常！",errorJson);
			tokenMap.put("code", 403);
			tokenMap.put("reason", "服务器错误");

			return IReadUtils.beanToJson(tokenMap);
		}
	}
	@Override
	public String addBindLogin(String user_identifier, String device_identifier,
			String nick_name, String source, String promot, String tokenStr,
			String image_url,String regist_ip,String sign) {
		UserInfo userInfo = new UserInfo();
		
		if(!StringUtils.isNullOrEmpty(sign)){
			String uuid=IReadUtils.getUserIdByToken(sign, ireadMemcacheService, device_identifier);
			String userStr =uuid+":"+device_identifier;
			String str = (String) ireadMemcacheService.get(userStr);
			if(!StringUtils.isNullOrEmpty(str)){
				
			}else{
				
			}
		}
		
		
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int temp=0;
		UsUser usUser = null;
		try {
			//获取相对应的绑定信息
			/*		UsUser usBand = usUserMapper.getSsoUserByUserIdentifier(user_identifier,Integer.valueOf(source));
			if (usBand == null) {
				usBand = new UsUser();
				usBand.setOpen_uid(user_identifier);
				usBand.setCreate_time(new Date());
				usBand.setModify_time(new Date());
				usBand.setBand_status(1);
				usBand.setOpen_id(Integer.valueOf(source));
				usBand.setUser_id(0L);
				temp=1;
			}else if(usBand.getBand_status()!=1){
				tokenMap.put("code", 403);
				tokenMap.put("reason", "账号被禁用");
			}
			//咪咕用户已存在数据表
			if(temp!=1){
				UsUser bandUser = usUserMapper.getCustomUserByUserid(usBand.getUser_id());
				if(bandUser!=null){
					usUser=bandUser;
				}
			}
			
			
			if(usUser==null){
				usUser = new UsUser();
				
				usUser.setCreate_time(new Date());
				usUser.setDevice_identifier(device_identifier);
				usUser.setImage_url(image_url);
				usUser.setIs_author(0);
				IdWorker worker2 = new IdWorker(7);
				usUser.setUser_id(worker2.nextId());
				usUser.setUser_name(usUser.getUser_id().toString());
				nick_name="书友_"+usUser.getUser_id();
				usUser.setUser_name(nick_name);
				usUser.setPromot_channel(promot);
				usUser.setRegist_ip(regist_ip);
				usUser.setRegist_source(Integer.valueOf(source));
				usUserMapper.addUser(usUser);
				usBand.setUser_id(usUser.getUser_id());
				usUserMapper.updateUserBand(usBand);
				UsBalance balance = new UsBalance();
				balance.setUser_id(usUser.getUser_id());
				balance.setBalance(IReadContent.register_balance);
				usBalanceMapper.addBalance(balance);
			}
			
			//转换成json
			
			//rsa加密
			String userStr = usUser.getUser_id()+":"+device_identifier;
			//rsa加密
			String signStr = IReadUtils.getSign(userStr);
			
			
			userInfo = setUser(usUser);
			
			
			//   System.out.println("sso:"+device_identifier+":"+signStr);
			ireadMemcacheService.setUserSignIn(usUser.getUser_id().toString()+device_identifier, signStr);*/
			tokenMap.put("code", 200);
			tokenMap.put("content", userInfo);
			//tokenMap.put("token", signStr);
			return IReadUtils.beanToJson(tokenMap);
		} catch (Exception e) {
			//String user_identifier, String device_identifier,
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("user_identifier", user_identifier);
			errorJson.put("device_identifier", device_identifier);
			errorJson.put("nick_name", nick_name);
			errorJson.put("source", source);
			errorJson.put("promot", promot);
			errorJson.put("promot", promot);
			errorJson.put("tokenStr", tokenStr);
			QSReadException.printf(e, "第三方登录异常！",errorJson);
			tokenMap.put("code", 403);
			tokenMap.put("reason", "服务器错误");
			
			return IReadUtils.beanToJson(tokenMap);
		}
	}
	@Override
	public String addThirdLogin(String user_identifier, String device_identifier,
			String nick_name, String source, String promot, String tokenStr,
			String image_url,String regist_ip) {
		UserInfo userInfo = new UserInfo();
		
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		int temp=0;
		UsUser usUser = null;
		try {
			//获取相对应的绑定信息
			UsUser usBand = usUserMapper.getSsoUserByUserIdentifier(user_identifier,Integer.valueOf(source));
			if (usBand == null) {
				usBand = new UsUser();
				usBand.setOpen_uid(user_identifier);
				usBand.setCreate_time(new Date());
				usBand.setModify_time(new Date());
				usBand.setBand_status(1);
				usBand.setOpen_id(Integer.valueOf(source));
				usBand.setUser_id(0L);
				temp=1;
			}else if(usBand.getBand_status()!=1){
				tokenMap.put("code", 403);
				tokenMap.put("reason", "账号被禁用");
			}
			//咪咕用户已存在数据表
			if(temp!=1){
				UsUser bandUser = usUserMapper.getCustomUserByUserid(usBand.getUser_id());
				if(bandUser!=null){
					usUser=bandUser;
				}
			}
			
			
			if(usUser==null){
				usBand.setUser_id(0L);
				String userStr = usBand.getOpen_uid()+":"+device_identifier;
				String signStr = IReadUtils.getSign(userStr);
				ireadMemcacheService.set(userStr,IReadContent.mobile_reset_passwd_effective_time, source);
				usUserMapper.updateUserBand(usBand);
				tokenMap.put("code", 1003);
				tokenMap.put("sign", signStr);
				tokenMap.put("reason", "用户未绑定");
				
				return IReadUtils.beanToJson(tokenMap);
			}
			
			//转换成json
			
			//rsa加密
			String userStr = usUser.getUser_id()+":"+device_identifier;
			//rsa加密
			String signStr = IReadUtils.getSign(userStr);
			
			
			userInfo = setUser(usUser);
			
			
			//   System.out.println("sso:"+device_identifier+":"+signStr);
			ireadMemcacheService.setUserSignIn(usUser.getUser_id().toString()+device_identifier, signStr);
			tokenMap.put("code", 200);
			tokenMap.put("content", userInfo);
			tokenMap.put("token", signStr);
			return IReadUtils.beanToJson(tokenMap);
		} catch (Exception e) {
			//String user_identifier, String device_identifier,
			Map<String,Object> errorJson = new HashMap<String,Object>();
			errorJson.put("user_identifier", user_identifier);
			errorJson.put("device_identifier", device_identifier);
			errorJson.put("nick_name", nick_name);
			errorJson.put("source", source);
			errorJson.put("promot", promot);
			errorJson.put("promot", promot);
			errorJson.put("tokenStr", tokenStr);
			QSReadException.printf(e, "第三方登录异常！",errorJson);
			tokenMap.put("code", 403);
			tokenMap.put("reason", "服务器错误");
			
			return IReadUtils.beanToJson(tokenMap);
		}
	}
	@Override
	public String sendEmail(String email,int type) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		UsUser user = usUserMapper.getCustomUserByEmail(email);
		if(null==user){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "用户不存在");
		}else{
			//rsa加密
			String userStr = user.getUser_id()+"";
			//rsa加密
			try {
				String signStr = "";
				if(ireadMemcacheService.getUserRestPsswd(user.getUser_id()+"")==null){
					signStr = IReadUtils.getSign(userStr);
					ireadMemcacheService.setUserRestPsswd(user.getUser_id().toString(), signStr);
				}else{
					signStr = (String) ireadMemcacheService.getUserRestPsswd(user.getUser_id()+"");
				}
				if(type==1){
					if(SendmailUtil.sendMail("勤书网账户密码重置", "亲爱的用户：<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您已申请勤书网密码修复服务，请点击下面的链接来重新设置密码：<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://m.iqinshu.cn/site/forget-token?sign="+signStr+" <br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;为确保您的账号安全，该链接仅24小时访问有效。如果丢失，请您前往勤书网重新使用密码修复服务。<br/><br/><br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如无法直接点击上述链接，请将以上链接复制到您的浏览器中打开。<br/><br/><br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;勤书网<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://m.iqinshu.com/"+"<br/>"
						    +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【注意】本邮件为系统自动发送，请不要回复。", email)){
						tokenMap.put("code", 200);
						tokenMap.put("success","发送成功");
					}else{
						tokenMap.put("code", 403);
						tokenMap.put("reason", "发送失败");
					}
				}else{
					if(SendmailUtil.sendMail("勤书网账户密码重置", "亲爱的用户：<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您已申请勤书网密码修复服务，请点击下面的链接来重新设置密码：<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://www.iqinshu.cn/user/forget-token?sign="+signStr+" <br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;为确保您的账号安全，该链接仅24小时访问有效。如果丢失，请您前往勤书网重新使用密码修复服务。<br/><br/><br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如无法直接点击上述链接，请将以上链接复制到您的浏览器中打开。<br/><br/><br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;勤书网<br/>"
							+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://www.iqinshu.com/"+"<br/>"
						    +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;【注意】本邮件为系统自动发送，请不要回复。", email)){
						tokenMap.put("code", 200);
						tokenMap.put("success","发送成功");
					}else{
						tokenMap.put("code", 403);
						tokenMap.put("reason", "发送失败");
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String checkSign(String sign, int type) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(StringUtils.isNullOrEmpty(sign)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "参数错误");
			return IReadUtils.beanToJson(tokenMap);
		}else{
			try {
				String user_id =new String(DESCoder.decrypt(DESCoder.decryptBASE64(URLDecoder.decode(sign,"UTF-8")), IReadContent.dec_password));
				if(sign.equals((String)ireadMemcacheService.getUserRestPsswd(user_id))){
					UsUser user = usUserMapper.getCustomUserByUserid(Long.valueOf(user_id));
					if(null!=user){
						tokenMap.put("code", 200);
						tokenMap.put("success","请求可用");
						return IReadUtils.beanToJson(tokenMap);
					}
				}
				
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			tokenMap.put("code", 403);
			tokenMap.put("reason", "验证码异常");
			return IReadUtils.beanToJson(tokenMap);
		}
		
		
	}
	@Override
	public String resetPasswd(String sign,String passwd) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(StringUtils.isNullOrEmpty(sign)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "参数错误");
			return IReadUtils.beanToJson(tokenMap);
		}else{
			try {
				String user_id =new String(DESCoder.decrypt(DESCoder.decryptBASE64(URLDecoder.decode(sign,"UTF-8")), IReadContent.dec_password));
				if(sign.equals((String)ireadMemcacheService.getUserRestPsswd(user_id))){
					UsUser user = usUserMapper.getCustomUserByUserid(Long.valueOf(user_id));
					if(null!=user){
						user.setUser_password(MD5.getMD5(MD5.getMD5(passwd)));
						usUserMapper.updateUserPasswd(user);
						ireadMemcacheService.deleteUserRestPsswd(user_id);
						tokenMap.put("code", 200);
						tokenMap.put("success","修改成功");
						return IReadUtils.beanToJson(tokenMap);
					}
					
				}else{
					tokenMap.put("code", 403);
					tokenMap.put("reason", "验证链接失效");
					return IReadUtils.beanToJson(tokenMap);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		tokenMap.put("code", 403);
		tokenMap.put("reason", "修改失败");
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String checkEmail(String email) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(StringUtils.isNullOrEmpty(email)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "邮箱不能为空");
		}else{
			Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
			Matcher matcher = pattern.matcher(email);
			if(matcher.matches()){
				UsUser user = usUserMapper.getCustomUserByEmail(email);
				if(user==null){
					tokenMap.put("code", 200);
					tokenMap.put("reason", "邮箱可用");
				}else{
					tokenMap.put("code", 403);
					tokenMap.put("reason", "邮箱已被占用");
				}
			}else{
				tokenMap.put("code", 403);
				tokenMap.put("reason", "邮箱格式不正确");
			}
		}
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String checkUser(String user_name) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		if(StringUtils.isNullOrEmpty(user_name)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "用户名不能为空");
		}else{
		
				UsUser user = usUserMapper.getCustomUserByUsername(user_name);
				if(user==null){
					tokenMap.put("code", 200);
					tokenMap.put("reason", "用户名可用");
				}else{
					tokenMap.put("code", 403);
					tokenMap.put("reason", "用户名已被占用");
				}
		
		}
		return IReadUtils.beanToJson(tokenMap);
	}
	@Override
	public String resetUserInfo(String user_name, String mobile_num,
			String email,String token,String device_identifier,String new_password,String old_password) {
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		String user_id = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		if(StringUtils.isNullOrEmpty(user_id)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "用户为登陆");
			return IReadUtils.beanToJson(tokenMap);
		}
		//判断是否需要更新
		int temp = 0;
		UsUser usUser = usUserMapper.getCustomUserByUserid(Long.valueOf(user_id));
		UsUser newUser = new UsUser();
		newUser.setUser_id(usUser.getUser_id());
		//判断是佛需要更新密码
		if(!StringUtils.isNullOrEmpty(usUser.getUser_password())){
			if(!StringUtils.isNullOrEmpty(new_password)){
				if(!StringUtils.isNullOrEmpty(old_password)){
					if(!usUser.getUser_password().equals(MD5.getMD5(MD5.getMD5(old_password)))){
						tokenMap.put("code", 403);
						tokenMap.put("reason", "原密码错误");
						return IReadUtils.beanToJson(tokenMap);
					}else{
						newUser.setUser_password(MD5.getMD5(MD5.getMD5(new_password)));
						temp=1;
					}
				}
			}
		}else{
			if(!StringUtils.isNullOrEmpty(old_password)){
				tokenMap.put("code", 403);
				tokenMap.put("reason", "第三方登录首次修改密码无需输入原始密码");
				return IReadUtils.beanToJson(tokenMap);
			}else{
				if(!StringUtils.isNullOrEmpty(new_password)){
					newUser.setUser_password(MD5.getMD5(MD5.getMD5(new_password)));
					temp=1;
				}
			}
		}
		//判断是否需要更新用户名
		if(!StringUtils.isNullOrEmpty(user_name)){
			if(!user_name.equals(usUser.getUser_name())){
				UsUser ex_user = usUserMapper.getCustomUserByUsername(user_name);
				if(ex_user==null){
					newUser.setUser_name(user_name);
					temp=1;
				}else{
					if(ex_user.getUser_id()!=usUser.getUser_id()){
						tokenMap.put("code", 403);
						tokenMap.put("reason", "用户已存在");
						return IReadUtils.beanToJson(tokenMap);
					}
				}
			}
			
		}
		//判断是否更新邮箱
		if(!StringUtils.isNullOrEmpty(email)){
			if(!email.equals(usUser.getEmail())){
				UsUser ex_user = usUserMapper.getCustomUserByEmail(email);
				if(ex_user==null){
					newUser.setEmail(email);
					temp=1;
				}
			}
			
		}
		//判断是否更新邮箱
		if(!StringUtils.isNullOrEmpty(mobile_num)){
			UsUser ex_user = usUserMapper.getCustomUserByMobile(mobile_num);
			if(ex_user==null){
				newUser.setMobile_num(mobile_num);
				temp=1;
			}
		}
		if(temp==1){
			usUserMapper.updateUser(newUser);
		}
		tokenMap.put("code", 200);
		tokenMap.put("content", "更新成功");
		return IReadUtils.beanToJson(tokenMap);
	}

	private UserInfo setUser(UsUser user){
		UserInfo userInfo = new UserInfo();
		userInfo.setCreate_time(DateUtil.getString(user.getCreate_time(),"yyyy-MM-dd HH:mm:ss"));
		userInfo.setEmail(user.getEmail());
		userInfo.setMobile_num(user.getMobile_num());
	//	userInfo.setModify_time(DateUtil.getString(user.getModify_time(),"yyyy-MM-dd HH:mm:ss"));
		userInfo.setUser_id(user.getUser_id()+"");
		userInfo.setUser_name(user.getUser_name());
		userInfo.setImage_url(IReadContent.portrait_url+user.getImage_url());
		if(StringUtils.isNullOrEmpty(userInfo.getImage_url())){
			
		}
		int stat_day = Integer.valueOf(DateUtil.getString(new Date(), "yyyyMMdd"));
		UsMemberVotes usMemberVotes = usMemberVotesMapper.getVotes(user.getUser_id(), stat_day);		
		if(usMemberVotes!=null){
			userInfo.setVotes(IReadUtils.getTotalVotes((long) user.getPoint(), ireadMemcacheService, userGradeMapper)-usMemberVotes.getUsed_votes());
		}else{
			userInfo.setVotes(IReadUtils.getTotalVotes((long) user.getPoint(), ireadMemcacheService, userGradeMapper));
		}
		if(null==user.getAuthor_id()){
			userInfo.setIs_author(0);
		}else if(user.getChecked()==0){
			userInfo.setIs_author(2);
		}else if(user.getChecked()==1){
			userInfo.setIs_author(1);
		}else{
			userInfo.setIs_author(3);
		}
		/*UsBalance balance = usBalanceMapper.getBalance(user.getUser_id());
		if(null==balance){
			balance = new UsBalance();
			balance.setBalance(0);
		}*/
		userInfo.setBalance(user.getBalance());
		userInfo.setPoint(user.getPoint());
		return userInfo;
	}
	@Override
	public String getRecharge(int type, int pages, int contents,
			String device_identifier, String token) {
		if(pages==0){
			pages=1;
		}
		if(contents==0){
			contents=20;
		}
		int index=(pages-1)*contents;
		Map<String,Object> tokenMap = new HashMap<String,Object>();
		String user_id = IReadUtils.getUserIdByToken(token, ireadMemcacheService, device_identifier);
		if(StringUtils.isNullOrEmpty(user_id)){
			tokenMap.put("code", 403);
			tokenMap.put("reason", "用户为登陆");
			return IReadUtils.beanToJson(tokenMap);
		}
		List<UsAccountRecharge> list = usRechargeMapper.getAccountsByUserid(index, contents, Long.valueOf(user_id), type);
		List<AccountRecharge> contentList= new ArrayList<AccountRecharge>();
		for(UsAccountRecharge usAccountRecharge :list){
			AccountRecharge accountRecharge = new AccountRecharge();
			accountRecharge.setCharge_fee(usAccountRecharge.getCharge_fee());
			accountRecharge.setCreate_time(DateUtil.getString(usAccountRecharge.getCreate_time(), "yyyy-MM-dd HH:mm:ss"));
			if(usAccountRecharge.getOrder_status()==1){
				accountRecharge.setOrder_status("交易创建");
			}else if(usAccountRecharge.getOrder_status()==2){
				accountRecharge.setOrder_status("交易成功");
			} else if(usAccountRecharge.getOrder_status()==3){
				accountRecharge.setOrder_status("交易失败");
			}
			if(usAccountRecharge.getPay_org_id()==1){
				accountRecharge.setPay_org_id("支付宝充值");
			}
			
			accountRecharge.setPay_order_no(usAccountRecharge.getPay_order_no());
			accountRecharge.setAcount_type("普通充值");
			accountRecharge.setOriginal_fee(usAccountRecharge.getOriginal_fee());
			contentList.add(accountRecharge);
		}
		PageData<AccountRecharge>page = new  PageData<AccountRecharge>();
		page.setContent(contentList);
		page.setCode(200);
		page.setPageNumber(pages);
		page.setPageSize(contents);
		page.setTotal(usRechargeMapper.getAccountsByUseridNum(Long.valueOf(user_id), type));
		return IReadUtils.beanToJson(page);
	}
	
	
	
}
